package com.ruoyi.common.wx.interceptor;

import com.ruoyi.common.exception.AppUnWorkTokenException;
import com.ruoyi.common.wx.domain.WxUser;
import com.ruoyi.common.wx.domain.WxUserToken;
import com.ruoyi.common.wx.service.IWxUserService;
import com.ruoyi.common.wx.service.IWxUserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class AppAuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    IWxUserTokenService wxUserTokenService;
    @Autowired
    IWxUserService wxUserService;

    public static final String USER_KEY = "appUserId";

    private static final List<String> noAuthUris = new ArrayList<String>() {{
        add("/app/user/loginOrRegister");
    }};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (noAuthUris.contains(request.getRequestURI())) return true;

        //获取用户凭证
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("Authorization");
        }

        //凭证为空
        if (StringUtils.isBlank(token)) {
            throw new AppUnWorkTokenException("请求此接口，缺少认证信息！");
        }

        WxUserToken userToken = wxUserTokenService.query().eq("token", token).one();

        if (token == null || userToken == null || userToken.getExpireTime() == null || userToken.getExpireTime().before(new Date())) {
            throw new AppUnWorkTokenException("认证失效，请重新登录！");
        }

        WxUser user = wxUserService.getById(userToken.getUserId());
        if (user == null) {
            throw new AppUnWorkTokenException("认证失效，请重新登录！");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, userToken.getUserId());

        /**
         * 续token有效期
         */
        if (request.getRequestURI().contains("/app/user/refreshToken")) {
            wxUserTokenService.refreshToken(userToken);
        }
        return true;
    }
}
